package test;

import java.io.*;
import javax.sound.midi.*;
import java.util.*;

public class MidiPlayer2
{
  private static void play(String fileName, int deviceNo)
    throws Exception
  {
    // open midi out device
    MidiDevice.Info [] midiDevices = MidiSystem.getMidiDeviceInfo();
    if(deviceNo < 0 || deviceNo >= midiDevices.length) {
      throw new IllegalArgumentException("Midi device number out of range");
    }
    MidiDevice midiDevice = MidiSystem.getMidiDevice(midiDevices[deviceNo]);
    midiDevice.open();
    // open sequencer
    Sequencer sequencer = MidiSystem.getSequencer(true);
    Transmitter trans = sequencer.getTransmitter();
    sequencer.open();
    // connect sequencer and midi out device
    trans.setReceiver(midiDevice.getReceiver());
    // play sequence
    Sequence seq = MidiSystem.getSequence(new File(fileName));
    sequencer.setSequence(seq);
    sequencer.start();
    // wait till end of sequence
    while(sequencer.isRunning()) {
      Thread.sleep(100);
    }
    // close all
    sequencer.stop();
    sequencer.close();
    midiDevice.close();
  }

  public static void main(String[] args) {
	  System.out.println("asdf");
    if(args.length != 2) {  // show help and device info
      System.out.println("Usage:");
      System.out.println("java MidiPlayer [midiFile] [deviceNumber]");
      System.out.println("");
      System.out.println("Midi Devices:");
      MidiDevice.Info [] midiDevices = MidiSystem.getMidiDeviceInfo();
      for(int i = 0; i < midiDevices.length; i++) {
        System.out.println("" + (i + 1) + " " + midiDevices[i].toString());
      }
      System.out.println("");
    } else {  // play midi
      try {
        play(args[0], 7);
      } catch(Exception e) {
        e.printStackTrace();
        System.exit(1);
      }
    }
    System.exit(0);
  }
}
